import { getBaseConfig } from '@/api/user'

const state = {
  moduleMessageEnable: false, // 是否启用消息模块,false:不启用;true:启用
  moduleEnableReport: false, // 是否启用报告模块,false:不启用;true:启用
  moduleEnableDetection: false, // 是否启用检测管理模块,false:不启用;true:启用
  moduleEnableSample: false, // 是否启用样品模块,false:不启用;true:启用
  moduleEnableEntrust: false // 是否启用委托模块,false:不启用;true:启用
}

const mutations = {
  SET_ModuleMessageEnable: (state, moduleMessageEnable) => {
    state.moduleMessageEnable = moduleMessageEnable
  },
  SET_ModuleEnableReport: (state, moduleEnableReport) => {
    state.moduleEnableReport = moduleEnableReport
  },
  SET_ModuleEnableDetection: (state, moduleEnableDetection) => {
    state.moduleEnableDetection = moduleEnableDetection
  },
  SET_ModuleEnableSample: (state, moduleEnableSample) => {
    state.moduleEnableSample = moduleEnableSample
  },
  SET_ModuleEnableEntrust: (state, moduleEnableEntrust) => {
    state.moduleEnableEntrust = moduleEnableEntrust
  }
}

const actions = {
  // 请求后端接口,获取消息模块是否开启的值
  getBaseConfig({ commit, state }) {
    return new Promise((resolve, reject) => {
      getBaseConfig(state.token).then(response => {
        // 即使后台没有拿到getBaseConfig接口,也要系统能正常工作
        const { data } = response
        let moduleMessageEnable = false
        let moduleEnableReport = false
        let moduleEnableDetection = false
        let moduleEnableSample = false
        let moduleEnableEntrust = false
        if (data) {
          data.forEach(element => {
            switch (element.key) {
              case "ModuleMessageEnable":
                moduleMessageEnable = JSON.parse(element.value);
                break;
              case "ModuleEntrustEnable":
                moduleEnableEntrust = JSON.parse(element.value)
                break;
              case "ModuleSampleEnable":
                moduleEnableSample = JSON.parse(element.value)
                break;
              case "ModuleDetectionEnable":
                moduleEnableDetection = JSON.parse(element.value)
                break;
              case "ModuleReportEnable":
                moduleEnableReport = JSON.parse(element.value)
                break;
            }
          });
        }
        commit('SET_ModuleMessageEnable', moduleMessageEnable)
        commit('SET_ModuleEnableReport', moduleEnableReport)
        commit('SET_ModuleEnableDetection', moduleEnableDetection)
        commit('SET_ModuleEnableSample', moduleEnableSample)
        commit('SET_ModuleEnableEntrust', moduleEnableEntrust)
        resolve(data)
      }).catch(error => {
        // 即使后台没有拿到getBaseConfig接口,也要系统能正常工作
        resolve(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
